package tree;

/**
 * @description:
 * @author: walt-zhong
 * @createDate: 2021/4/13
 */
public class Tree {
    static class TreeNode{
        int data;
        TreeNode left;
        TreeNode right;

        public TreeNode(int data){
            this.data = data;
        }
    }

    /**
     * 寻找二叉树两个节点最近的公共父节点
     * @param root
     * @param treeNode1
     * @param treeNode2
     * @return
     */

    public static TreeNode getPath(TreeNode root,TreeNode treeNode1,TreeNode treeNode2){
        if(root == null || root == treeNode1 || root == treeNode2){
            return root;
        }

        TreeNode left = null;
        TreeNode right = null;

        if(root.left != null){
            left = getPath(root.left,treeNode1,treeNode2);
        }

        if(root.right != null){
            right = getPath(root.right,treeNode1,treeNode2);
        }

        if(left!= null && right != null){
            return root;
        }

        return left!=null?left:right;
    }

    public static void main(String[] args) {
        TreeNode treeNode1 = new TreeNode(1);
        TreeNode treeNode2 = new TreeNode(2);
        TreeNode treeNode3 = new TreeNode(3);
        TreeNode treeNode4 = new TreeNode(4);
        TreeNode treeNode5 = new TreeNode(5);

        treeNode1.left = treeNode2;
        treeNode1.right = treeNode3;
        treeNode2.left = treeNode4;
        treeNode2.right = treeNode5;

        TreeNode treeNode9 = getPath(treeNode1,treeNode4,treeNode3);
        System.out.println("result: " + treeNode9.data);

    }
}
